/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2023-03-07
 * Time: 20:26
 */
public class HashBucket {
    private static class Node {
        private int key;
        private int val;
        Node next;


        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }


    private Node[] array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 10;//默认桶的大小

    public HashBucket() {
        this.array = new Node[DEFAULT_SIZE];
    }

    public void put(int key, int value) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if(cur.val == value) {
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key, value);
        node.next = array[index];
        array[index] = node;
        size++;
        if(loadFactor() >= LOAD_FACTOR) {
            resize();
        }
    }


    private void resize() {
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
